package com.time.admin.application.controller;

import com.time.admin.application.converter.CacheAdminDTOConverter;
import com.time.admin.application.dto.CacheKeyItemDTO;
import com.time.admin.application.dto.CacheMetricsDTO;
import com.time.admin.domain.entity.CacheKeyItemBO;
import com.time.admin.domain.entity.CacheMetricsBO;
import com.time.admin.domain.service.AdminCacheDomainService;
import com.time.auth.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 缓存管理控制层类
 *
 * @author: HuangQi
 * @date: Created in 2025/01/XX
 * @description: 缓存管理控制层
 */
@Slf4j
@RestController
@RequestMapping("/admin/cache/")
public class CacheAdminController {

    @Autowired
    private AdminCacheDomainService adminCacheDomainService;

    /**
     * 获取缓存总体统计
     *
     * @param prefix 缓存前缀，可选参数
     * @return 缓存统计结果
     */
    @GetMapping("metrics")
    public Result<CacheMetricsDTO> metrics(@RequestParam(value = "prefix", required = false) String prefix) {
        try {
            if (log.isInfoEnabled()) {
                log.info("Admin.CacheAdminController.metrics.prefix:{}", prefix);
            }

            // 调用领域层
            CacheMetricsBO metrics = adminCacheDomainService.metrics(prefix);

            // 返回结果
            return Result.ok(CacheAdminDTOConverter.INSTANCE.toDTO(metrics));
        } catch (Exception e) {
            // 异常处理
            log.error("Admin.CacheAdminController.metrics.error:{}", e.getMessage(), e);
            return Result.fail("管理模块获取缓存统计失败");
        }
    }

    /**
     * 分页列出缓存键
     *
     * @param pattern 匹配模式，可选参数，默认为"*"
     * @param page 页码，从0开始
     * @param size 每页大小
     * @return 缓存键列表
     */
    @GetMapping("keys")
    public Result<List<CacheKeyItemDTO>> listKeys(@RequestParam(value = "pattern", required = false) String pattern,
                                                  @RequestParam(value = "page", defaultValue = "0") int page,
                                                  @RequestParam(value = "size", defaultValue = "20") int size) {
        try {
            if (log.isInfoEnabled()) {
                log.info("Admin.CacheAdminController.listKeys.pattern:{}, page:{}, size:{}", pattern, page, size);
            }

            // 调用领域层
            List<CacheKeyItemBO> list = adminCacheDomainService.listKeys(pattern, page, size);

            // 返回结果
            return Result.ok(CacheAdminDTOConverter.INSTANCE.toDTOList(list));
        } catch (Exception e) {
            // 异常处理
            log.error("Admin.CacheAdminController.listKeys.error:{}", e.getMessage(), e);
            return Result.fail("管理模块获取缓存键失败");
        }
    }

    /**
     * 删除单个缓存键
     *
     * @param key 要删除的缓存键
     * @param confirm 确认标识，危险操作需要 confirm=true
     * @return 删除结果
     */
    @DeleteMapping("entries/{key}")
    public Result<Boolean> evict(@PathVariable("key") String key,
                                 @RequestParam(value = "confirm", defaultValue = "false") boolean confirm) {
        try {
            if (log.isInfoEnabled()) {
                log.info("Admin.CacheAdminController.evict.key:{}, confirm:{}", key, confirm);
            }

            // 参数校验
            if (!confirm) {
                return Result.fail("危险操作需要 confirm=true");
            }

            // 调用领域层
            Boolean evictResult = adminCacheDomainService.evict(key);

            // 返回结果
            return Result.ok(evictResult);
        } catch (Exception e) {
            // 异常处理
            log.error("Admin.CacheAdminController.evict.error:{}", e.getMessage(), e);
            return Result.fail("管理模块删除缓存键失败");
        }
    }

    /**
     * 按模式批量删除缓存键
     *
     * @param pattern 匹配模式
     * @param confirm 确认标识，危险操作需要 confirm=true
     * @return 删除的缓存键数量
     */
    @DeleteMapping("entries")
    public Result<Long> evictByPattern(@RequestParam("pattern") String pattern,
                                       @RequestParam(value = "confirm", defaultValue = "false") boolean confirm) {
        try {
            if (log.isInfoEnabled()) {
                log.info("Admin.CacheAdminController.evictByPattern.pattern:{}, confirm:{}", pattern, confirm);
            }

            // 参数校验
            if (!confirm) {
                return Result.fail("危险操作需要 confirm=true");
            }

            // 调用领域层
            Long evictCount = adminCacheDomainService.evictByPattern(pattern);

            // 返回结果
            return Result.ok(evictCount);
        } catch (Exception e) {
            // 异常处理
            log.error("Admin.CacheAdminController.evictByPattern.error:{}", e.getMessage(), e);
            return Result.fail("管理模块批量删除缓存失败");
        }
    }

    /**
     * 清空缓存（可选前缀）
     *
     * @param prefix 缓存前缀，可选参数，不传则清空全部
     * @param confirm 确认标识，危险操作需要 confirm=true
     * @return 删除的缓存键数量
     */
    @PostMapping("evict-all")
    public Result<Long> evictAll(@RequestParam(value = "prefix", required = false) String prefix,
                                 @RequestParam(value = "confirm", defaultValue = "false") boolean confirm) {
        try {
            if (log.isInfoEnabled()) {
                log.info("Admin.CacheAdminController.evictAll.prefix:{}, confirm:{}", prefix, confirm);
            }

            // 参数校验
            if (!confirm) {
                return Result.fail("危险操作需要 confirm=true");
            }

            // 调用领域层
            Long evictCount = adminCacheDomainService.evictAll(prefix);

            // 返回结果
            return Result.ok(evictCount);
        } catch (Exception e) {
            // 异常处理
            log.error("Admin.CacheAdminController.evictAll.error:{}", e.getMessage(), e);
            return Result.fail("管理模块清空缓存失败");
        }
    }
}


